package Utils.word;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

/**
 * Created by 隼 on 2017/6/2.
 *Jacob
 * word转换成HTML
 * 测试        WordReader.extractDoc("C:\\Users\\隼\\Desktop\\test.docx","C:\\Users\\隼\\Desktop\\test.html");

 */
public class WordReader {

    public static void extractDoc(String inputFIle, String outputFile) {
        boolean flag = false;
        // 打开Word应用程序
        ActiveXComponent app = new ActiveXComponent("Word.Application");
        try {
            // 设置word不可见
            app.setProperty("Visible", new Variant(false));
            // 打开word文件
            Dispatch doc1 = app.getProperty("Documents").toDispatch();
            Dispatch doc2 = Dispatch
                    .invoke(doc1, "Open", Dispatch.Method, new Object[] {inputFIle, new Variant(false), new Variant(true)},
                            new int[1]).toDispatch();
            // 作为html格式保存到临时文件：：参数 new Variant(8)其中8表示word转html;7表示word转txt;44表示Excel转html。。。
            Dispatch.invoke(doc2, "SaveAs", Dispatch.Method, new Object[] {outputFile, new Variant(8)}, new int[1]);
            // 关闭word
            Variant f = new Variant(false);
            Dispatch.call(doc2, "Close", f);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            app.invoke("Quit", new Variant[] {});
        }
        if (flag == true) {
            System.out.println("Transformed Successfully");
        } else {
            System.out.println("Transform Failed");
        }
    }
}
